var mmlog = require("../sever/mmlog").root("[routes/sys.js]");
var http=require("http");
var express = require('express');
var router = express.Router();
var util = require("../sever/util");
var config = require("../sever/config");
var wxapi = require("../sever/channel/WeChat-API");
var fs = require("fs");
var multiparty = require('connect-multiparty');
var io = require("../sever/socket");

var pluginManager = require("../sever/pluginManager");

router.get('/plu/load', function(req, res, next) {
	var d = pluginManager.load();
	res.json({
		total: d.length,
		rows: d
	})
});
router.get('/wx/menu/create', function(req, res, next) {
	wxapi.addMenu(config.business(), function(data) {
		res.json(data);
	});
});

router.post("/plu/upload", multiparty(), function(req, res) {
	var root = "./client/plugins/";
	var _ufile = req.files.ufile;
	fs.readFile(_ufile.path, function(error, data) {
		if (!error) {
			console.log("读取文件成功...");
			var filePath = root + _ufile.name;
			fs.writeFile(filePath, data, function(error, _data) {
				util.unzip(filePath, root, function() {
					pluginManager.reload(function(data) {
						console.log("all");
						io.all(data);
					});
					res.type("application/json");
					res.send({
						code: 0
					});
				});
			})
		} else {
			console.log("读取文件失败...");
		}
	})
});

/**
 * 加载在线插件
 */
router.get("/ol/plu", function(req, res) {
	util.get("http://localhost:8099/files",function(r){
		res.json({
			total: r.des.length,
			rows: r.des
		})
	})
})

/**
 * 在线安装插件
 */
router.post("/ol/i/plu", function(req, res) {
	var root = "./client/plugins/";
	var p = req.body.path;
	var name = p+".zip";
	if (p) {
		var writestream = fs.createWriteStream(root + name);
		http.get("http://localhost:8099/down/"+name, function(_res) {
			_res.pipe(writestream);
		});
		writestream.on('finish', function() {
			util.unzip(root + name, root, function() {
				pluginManager.reload(function(data) {
					io.all(data);
				});
				res.json({
					code: 0
				});
			});
		});
	}
})

module.exports = router;